﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ECommon
{
    /// <summary>
    /// Udp协议工具
    /// </summary>
    public static partial class UdpTool
    {
        /// <summary>
        /// upd客户端
        /// </summary>
        private static UdpClient _client = null;

        /// <summary>
        /// upd发送客户端
        /// </summary>
        private static UdpClient _sendClient = null;

        /// <summary>
        /// 获取udp客户端
        /// </summary>
        /// <param name="ipAddress">ip地址</param>
        /// <param name="port">通信端口</param>
        /// <returns>udp客户端</returns>
        /// <exception cref="ArgumentException">端口设定异常</exception>
        /// <exception cref="ArgumentNullException">ip地址为空异常</exception>
        public static UdpClient GetUdpClient(IPAddress ipAddress, int port)
        {
            if (port <= 0 && port > 65535)
            {
                throw new ArgumentException("获取Udp通信客户端时，端口设定参数超出范围");
            }
            if (ipAddress == null)
            {
                throw new ArgumentNullException("获取Upd通信客户端时，没有指定ip地址");
            }
            if (_client == null)
            {
                _client = new UdpClient(new IPEndPoint(ipAddress, port));
            }
            return _client;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public static void DisposeUdpClient()
        {
            if (_sendClient != null)
            {
                _sendClient.Dispose();
            }
        }

        /// <summary>
        /// udp发送消息
        /// </summary>
        /// <param name="utf8Str">要发送的数据，utf8编码</param>
        /// <param name="remoteEndPoint">远程数据接收端</param>
        /// <exception cref="ArgumentNullException">变量为空异常</exception>
        public static void UpdSend(string utf8Str, IPEndPoint remoteEndPoint)
        {
            if (string.IsNullOrWhiteSpace(utf8Str))
            {
                throw new ArgumentNullException("Udp客户端发送的数据为空");
            }
            if (remoteEndPoint == null)
            {
                throw new ArgumentNullException("目标服务器不可为空");
            }
            if (_sendClient == null)
            {
                _sendClient = new UdpClient();
            }
            // 要发送的数据
            byte[] data = Encoding.UTF8.GetBytes(utf8Str);
            lock (_udpLock)
            {
                // 发送数据
                _sendClient.Send(data, data.Length, remoteEndPoint);
            }
        }

        /// <summary>
        /// udp锁
        /// </summary>
        private static object _udpLock = new object();
    }
}
